<template>
  <div class="app-container">
    <!-- 统计卡片区 -->
    <el-row :gutter="20" class="stat-cards no-wrap-row fixed-width-row">
      <div v-for="stat in stats" :key="stat.title" class="stat-col fixed-stat-col">
        <el-card shadow="never" class="stat-card compact-stat-card">
          <div>
            <div class="stat-card-title">{{ stat.title }}</div>
            <div class="stat-card-num" :style="{ color: stat.color }">{{ stat.value }}</div>
          </div>
          <i :class="['stat-icon', stat.icon]" :style="{ color: stat.color }"></i>
        </el-card>
      </div>
    </el-row>

    <!-- 横向柱状图 -->
    <el-card shadow="hover" class="chart-card">
      <div slot="header" class="card-header">
        <span class="card-title">
          <i class="el-icon-data-line card-title-icon"></i>
          会议统计图表
        </span>
        <span style="display: inline-flex; align-items: center;">
          <span>月份选择：</span>
          <el-date-picker v-model="dateRange" type="monthrange" size="small" value-format="yyyy-MM"
            start-placeholder="开始月份" end-placeholder="结束月份" range-separator="至" unlink-panels
            @change="handleDateRangeChange" />
        </span>
      </div>
      <div id="bar-chart" class="chart-container"></div>
    </el-card>

    <!-- 表格区 -->
    <el-card shadow="hover" class="table-card">
      <div slot="header" class="card-header">
        <span class="card-title">
          <i class="el-icon-s-order card-title-icon"></i>
          未完成会议事项
        </span>
      </div>
      <el-table v-loading="loading" :data="tableData" border class="data-table"
        :header-cell-style="{ background: '#f5f8ff', color: '#409EFF' }" stripe>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="meetingName" label="会议名称" min-width="100" show-overflow-tooltip />
        <el-table-column prop="taskDescription" label="具体事项" min-width="100" show-overflow-tooltip />
        <el-table-column prop="responsibleUserName" label="负责人" width="120" align="center" />
        <el-table-column prop="dueDate" label="计划完成时间" width="120" align="center" />
        <el-table-column prop="checkerUserName" label="检查人" width="120" align="center" />
        <el-table-column prop="isDelay" label="延期情况" width="120" align="center">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isDelay === 1 ? 'danger' : 'success'" effect="plain" size="small">
              {{ scope.row.isDelay === 1 ? '延期' : '未延期' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="totalTasks" label="工作事项总数" width="120" align="center" /> -->
        <!-- <el-table-column prop="completedTasks" label="已完成事项数" width="120" align="center" /> -->
        <!-- <el-table-column prop="completionRate" label="完成率" width="100" align="center">
          <template slot-scope="scope">
            <span
              :style="{ color: scope.row.completionRate >= 80 ? '#67C23A' : scope.row.completionRate >= 50 ? '#E6A23C' : '#F56C6C' }">
              {{ scope.row.completionRate }}%
            </span>
          </template>
</el-table-column> -->
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="scope">
            <router-link :to="'/officeMeeting/meetingRecordDetail/index/' + scope.row.meetingId" class="link-type">
              <el-button size="mini" type="text" icon="el-icon-view" class="view-btn">查看详情</el-button>
            </router-link>
          </template>
        </el-table-column>
      </el-table>
      <!-- 暂无分页需求，如需分页可在此处补充 -->
    </el-card>
  </div>
</template>

<script>
import echarts from 'echarts'
import { meetingTotals } from "@/api/officeMeeting/meetingTask";

export default {
  name: "MeetingTotal",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 查询日期
      dateSearch: { dateQuery: '', endDateQuery: '' },
      dateRange: [],
      // 统计卡片数据
      stats: [
        { title: '会议总数', value: 0, icon: 'el-icon-s-order', color: '#409EFF' },
        { title: '工作事项总数', value: 0, icon: 'el-icon-document', color: '#67C23A' },
        { title: '已完成工作事项总数', value: 0, icon: 'el-icon-circle-check', color: '#E6A23C' },
        { title: '完成率', value: '0%', icon: 'el-icon-data-line', color: '#F56C6C' }
      ],
      // 表格数据
      tableData: [],
      // 图表数据
      chartData: {
        categories: [],
        values: []
      },
      // 图表实例
      chartInstance: null
    };
  },
  created() {
    this.getStatistics();
  },
  activated() {
    this.getStatistics();
  },
  mounted() {
    this.$nextTick(() => {
      this.renderBarChart();
    });
  },
  methods: {
    /** 获取统计数据 */
    getStatistics() {
      this.loading = true;
      const params = {
        dateQuery: this.dateSearch.dateQuery || '',
        endDateQuery: this.dateSearch.endDateQuery || ''
      };
      meetingTotals(params).then(response => {
        if (response.data) {
          const data = response.data;
          this.stats[0].value = data.count || 0;
          this.stats[1].value = data.taskCount || 0;
          this.stats[2].value = data.completedTaskCount || 0;

          const completionRateRaw = data.taskCompletionRate;
          let completionRateDisplay = '0%';
          if (typeof completionRateRaw === 'number') {
            const rateNumber = completionRateRaw > 1 ? completionRateRaw : completionRateRaw * 100;
            completionRateDisplay = `${rateNumber.toFixed(1)}%`;
          } else if (typeof completionRateRaw === 'string') {
            completionRateDisplay = completionRateRaw.includes('%') ? completionRateRaw : `${completionRateRaw}%`;
          }
          this.stats[3].value = completionRateDisplay;

          // 表格数据来源于未完成事项集合
          const unCompletedTaskList = Array.isArray(data.unCompletedTaskList) ? data.unCompletedTaskList : [];
          this.tableData = unCompletedTaskList.map(item => {
            const totalTasks = item.totalTasks ?? item.taskCount ?? 0;
            const completedTasks = item.completedTasks ?? item.completedTaskCount ?? 0;
            const completionRate = totalTasks > 0
              ? parseFloat(((completedTasks / totalTasks) * 100).toFixed(1))
              : 0;
            return {
              ...item,
              totalTasks,
              completedTasks,
              completionRate,
              meetingDate: item.meetingDate || item.dueDate || '--',
              meetingId: item.meetingId || item.id
            };
          });

          const hasDeptChart = this.updateChartDataFromDepartmentRate(data.departmentCompletionRateMap);
          if (!hasDeptChart && this.tableData.length > 0) {
            this.updateChartData();
          } else if (!hasDeptChart && this.tableData.length === 0) {
            // 如果没有未完成事项且无部门图表，尝试使用接口提供的图表数据
            if (data.chartData) {
              this.chartData = data.chartData;
              this.$nextTick(() => {
                this.renderBarChart();
              });
            } else {
              this.initDefaultChartData();
              this.$nextTick(() => {
                this.renderBarChart();
              });
            }
          }
        }
      }).catch(() => {
        // 如果接口失败，使用默认数据
        this.initDefaultChartData();
        this.$nextTick(() => {
          this.renderBarChart();
        });
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 日期范围筛选变化 */
    handleDateRangeChange(value) {
      const range = Array.isArray(value) ? value : [];
      this.dateRange = range;
      this.dateSearch.dateQuery = range[0] || '';
      this.dateSearch.endDateQuery = range[1] || '';
      this.getStatistics();
    },
    /** 根据部门完成率生成图表 */
    updateChartDataFromDepartmentRate(rateMap) {
      const categories = [];
      const values = [];

      if (Array.isArray(rateMap)) {
        rateMap.forEach(item => {
          if (item && typeof item === 'object') {
            const deptEntry = Object.entries(item).find(([key]) => key !== 'total' && key !== 'completed')
            if (deptEntry) {
              const [dept, rate] = deptEntry
              categories.push(dept);
              const total = Number.isFinite(Number(item.total)) ? Number(item.total) : undefined
              const completed = Number.isFinite(Number(item.completed)) ? Number(item.completed) : undefined
              const unfinished = (typeof total === 'number' && typeof completed === 'number')
                ? Math.max(total - completed, 0)
                : undefined
              const rateValue = this.normalizeRate(rate)
              values.push({
                value: rateValue,
                total,
                completed,
                unfinished
              })
            }
          }
        });
      } else if (rateMap && typeof rateMap === 'object') {
        Object.keys(rateMap).forEach(key => {
          categories.push(key);
          const rawValue = rateMap[key]
          if (rawValue && typeof rawValue === 'object') {
            const total = Number.isFinite(Number(rawValue.total)) ? Number(rawValue.total) : undefined
            const completed = Number.isFinite(Number(rawValue.completed)) ? Number(rawValue.completed) : undefined
            const unfinished = (typeof total === 'number' && typeof completed === 'number')
              ? Math.max(total - completed, 0)
              : undefined
            const rateValue = this.normalizeRate(rawValue.rate ?? rawValue.value ?? 0)
            values.push({
              value: rateValue,
              total,
              completed,
              unfinished
            })
          } else {
            const rateValue = this.normalizeRate(rawValue)
            values.push({ value: rateValue })
          }
        });
      }

      if (categories.length > 0) {
        this.chartData = { categories, values };
        this.$nextTick(() => {
          this.renderBarChart(true);
        });
        return true;
      }
      return false;
    },
    /** 规范化完成率为百分比数值 */
    normalizeRate(value) {
      if (typeof value === 'number') {
        return value > 1 ? Number(value.toFixed(2)) : Number((value * 100).toFixed(2));
      }
      if (typeof value === 'string') {
        const numeric = parseFloat(value.replace('%', ''));
        return isNaN(numeric) ? 0 : numeric;
      }
      return 0;
    },
    /** 更新图表数据 */
    updateChartData() {
      if (this.tableData.length > 0) {
        // 取前10条数据用于图表展示
        const chartDataList = this.tableData.slice(0, 10);
        this.chartData = {
          categories: chartDataList.map(item => item.meetingName || '未命名会议'),
          values: chartDataList.map(item => {
            const total = item.totalTasks || 0
            const completed = item.completedTasks || 0
            const unfinished = Math.max(total - completed, 0)
            return {
              value: total,
              total,
              completed,
              unfinished
            }
          })
        };
        this.$nextTick(() => {
          this.renderBarChart();
        });
      } else {
        // 数据为空时，清空图表数据并重新渲染
        this.initDefaultChartData();
        this.$nextTick(() => {
          this.renderBarChart();
        });
      }
    },
    /** 初始化默认图表数据 */
    initDefaultChartData() {
      this.chartData = {
        categories: [],
        values: []
      };
    },
    /** 渲染横向柱状图 */
    renderBarChart(isRateChart = false) {
      const chartDom = document.getElementById('bar-chart');
      if (!chartDom) return;

      // 如果图表实例不存在，则初始化
      let chart = this.chartInstance;
      if (!chart) {
        chart = echarts.init(chartDom);
        this.chartInstance = chart;

        // 窗口大小改变时自适应
        const resizeHandler = () => {
          if (this.chartInstance) {
            this.chartInstance.resize();
          }
        };
        window.addEventListener('resize', resizeHandler);

        // 组件销毁时清理
        this.$once('hook:beforeDestroy', () => {
          window.removeEventListener('resize', resizeHandler);
          if (this.chartInstance) {
            this.chartInstance.dispose();
            this.chartInstance = null;
          }
        });
      }

      const hasData = Array.isArray(this.chartData.categories) && this.chartData.categories.length > 0;
      if (!hasData) {
        // 数据为空时，显示默认空状态图表
        const emptyOption = {
          title: {
            text: '暂无数据',
            left: 'center',
            top: 'middle',
            textStyle: {
              color: '#909399',
              fontSize: 16,
              fontWeight: 'normal'
            }
          },
          xAxis: {
            type: 'value',
            show: false
          },
          yAxis: {
            type: 'category',
            show: false
          },
          series: []
        };
        chart.setOption(emptyOption, true);
        return;
      }
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: params => {
            const item = Array.isArray(params) ? params[0] : params
            if (!item) return ''
            const dataItem = item.data || {}
            const name = item.name || ''
            const value = (dataItem && typeof dataItem.value !== 'undefined') ? dataItem.value : item.value
            const lines = [name]
            const hasTotals = typeof dataItem.total === 'number' || typeof dataItem.completed === 'number'
            if (hasTotals) {
              lines.push(`总事项：${typeof dataItem.total === 'number' ? dataItem.total : value}`)
              if (typeof dataItem.completed === 'number') {
                lines.push(`已完成：${dataItem.completed}`)
              }
              if (typeof dataItem.unfinished === 'number') {
                lines.push(`未完成：${dataItem.unfinished}`)
              }
            }
            if (isRateChart) {
              lines.push(`完成率：${value}%`)
            } else if (!hasTotals) {
              lines.push(`数量：${value}`)
            }
            return lines.join('<br/>')
          }
        },
        grid: {
          left: '3%',
          right: '6%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: isRateChart ? '完成率(%)' : '数量',
          axisLabel: {
            formatter: isRateChart ? '{value}%' : '{value}'
          },
          max: isRateChart ? 100 : null
        },
        yAxis: {
          type: 'category',
          data: this.chartData.categories,
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        series: [
          {
            name: isRateChart ? '完成率' : '工作事项数',
            type: 'bar',
            data: this.chartData.values,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 1, 0, [
                { offset: 0, color: '#409EFF' },
                { offset: 1, color: '#6ec6ff' }
              ]),
              borderRadius: [0, 8, 8, 0]
            },
            label: {
              show: true,
              position: 'right',
              formatter: params => {
                const val = params.data && typeof params.data.value !== 'undefined'
                  ? params.data.value
                  : params.value
                return isRateChart ? `${val}%` : `${val}`
              }
            }
          }
        ]
      };

      chart.setOption(option, true); // 使用 notMerge: true 确保完全替换旧配置
    }
  }
};
</script>

<style lang="scss" scoped>
.app-container {
  padding: 10px;
  background: linear-gradient(135deg, #eaf6ff 0%, #f5f8ff 100%);
  min-height: calc(100vh - 84px);
  font-family: 'PingFang SC', 'Microsoft YaHei', Arial, sans-serif;
  color: #222;
  background-image: repeating-linear-gradient(135deg, rgba(64, 158, 255, 0.03) 0 2px, transparent 2px 40px);
}

.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  position: relative;
  background: #fff;
  border-radius: 22px;
  box-shadow: 0 4px 24px rgba(64, 158, 255, 0.10);
  border: 1px solid #eaf4ff;

  .el-card__body {
    display: flex;
    flex-direction: column;
    align-items: flex-start;
    justify-content: flex-start;
    min-height: 80px;
    padding-right: 60px;
  }

  .stat-icon {
    position: absolute;
    right: 16px;
    top: 16px;
    font-size: 48px;
    pointer-events: none;
    z-index: 1;
  }

  .stat-card-title {
    color: #606266;
    font-size: 14px;
    margin-bottom: 10px;
    font-weight: 500;
    z-index: 2;
  }

  .stat-card-num {
    font-size: 32px;
    font-weight: bold;
    z-index: 2;
    position: relative;
  }
}

.no-wrap-row {
  flex-wrap: nowrap !important;
  overflow-x: auto;
}

.stat-col {
  min-width: 160px;
}

.compact-stat-card .el-card__body {
  min-height: 60px;
  padding-right: 40px;
  padding-top: 10px;
  padding-bottom: 10px;
}

.stat-card-title {
  font-size: 13px;
  margin-bottom: 6px;
}

.stat-card-num {
  font-size: 24px;
}

.stat-icon {
  font-size: 32px !important;
  top: 10px !important;
  right: 10px !important;
}

.fixed-width-row {
  flex-wrap: nowrap !important;
  overflow-x: visible;
  display: flex;
  gap: 20px 20px;
  /* 行间和列间间隙 */
}

.fixed-stat-col {
  flex: 1;
  min-width: 185px;
  /* 让每个卡片平均分配空间，在一行铺满 */
}

.fixed-stat-col:last-child {
  margin-right: 0;
}

.chart-card,
.table-card {
  margin-top: 20px;
  border-radius: 22px;
  border: 1px solid #eaf4ff;
  background: #fff;
  box-shadow: 0 4px 24px rgba(64, 158, 255, 0.10);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 6px 32px rgba(64, 158, 255, 0.15) !important;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px 20px;
    border-bottom: 1px solid #eaf4ff;
  }

  .card-title {
    font-size: 19px;
    font-weight: bold;
    color: #222;
    display: flex;
    align-items: center;
    gap: 8px;
    letter-spacing: 1.2px;

    .card-title-icon {
      font-size: 18px;
      color: #409EFF;
    }
  }
}

.chart-container {
  width: 100%;
  height: 320px;
  padding: 20px;
}

.data-table {
  border-radius: 4px;
  overflow: hidden;

  ::v-deep .el-table__header {
    th {
      background: #f5f8ff !important;
      color: #409EFF;
      font-weight: 600;
      font-size: 16px;
      padding: 12px 0;
      border-bottom: 1px solid #eaf4ff;
      letter-spacing: 0.5px;
    }
  }

  ::v-deep .el-table__body {
    tr {
      transition: background-color 0.2s ease;
      border-radius: 12px;

      &:hover {
        background: #eaf4ff !important;
      }
    }

    td {
      padding: 12px 0;
      border-bottom: 1px solid #f0f3fa;
      font-size: 16px;
    }
  }

  ::v-deep .el-table__border {
    border-color: #eaf4ff;
  }

  ::v-deep .el-table td,
  ::v-deep .el-table th {
    border-color: #eaf4ff;
  }
}

.link-type {
  text-decoration: none;
  transition: all 0.2s ease;

  .view-btn {
    color: #409EFF;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.2s ease;

    &:hover {
      color: #66b1ff;
      background-color: #ecf5ff;
    }
  }
}

// 响应式设计
@media (max-width: 1100px) {
  .stat-cards {
    .fixed-stat-col {
      width: 50% !important;
      max-width: 50% !important;
      flex: 0 0 50% !important;
    }
  }
}

@media (max-width: 700px) {
  .app-container {
    padding: 12px;
  }

  .stat-cards {
    margin-bottom: 16px;

    .fixed-stat-col {
      width: 100% !important;
      max-width: 100% !important;
      flex: 0 0 100% !important;
    }
  }

  .chart-card,
  .table-card {
    margin-top: 16px;
  }

  .chart-container {
    height: 280px;
    padding: 16px;
  }
}
</style>
